﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FinApp.DataProviders.Configuration;
using System.Text;
using FinApp.Core;
using System.Runtime.Serialization.Json;
using FinApp.Model;
using FinApp.DataProviders.EventArguments;
using FinApp.DataProviders.Enumerations;

namespace FinApp.DataProviders {
    public class LoginProvider : Singleton<LoginProvider> {

        #region Events
        public event LoginCompleteEventHandler LoginCompleted;
        #endregion

        #region Members
        private DataContractJsonSerializer serializer;
        #endregion

        #region Constructors
        public LoginProvider() {
            this.serializer = new DataContractJsonSerializer(typeof(LoginModel));
        }
        #endregion

        #region Methods
        public void DoLoginAsync(string userName, string userPassword) {
            WebClient webClient = new WebClient();
            this.SetBasicAuthHeader(webClient, userName, userPassword);
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted);
            webClient.OpenReadAsync(new Uri(ConfigurationProvider.Instance.GetApiUrl() + "/access/login"));
        }

        private void SetBasicAuthHeader(WebClient req, string userName, string userPassword) {
            string authInfo = userName + ":" + userPassword;
            authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
            req.Headers["Authorization"] = "Basic " + authInfo;
        }

        #endregion

        #region Events

        private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
            WebClient webClient = sender as WebClient;
            webClient.OpenReadCompleted -= new OpenReadCompletedEventHandler(OnOpenReadCompleted);
            LoginModel loginModel = (LoginModel)serializer.ReadObject(e.Result);
            if (loginModel.Status == "OK") {
                ConfigurationProvider.Instance.Token = loginModel.Token;
            }
            if (this.LoginCompleted != null) {
                switch (loginModel.Status) {
                    case "OK":
                        this.LoginCompleted(this, new LoginEventArgs(ProviderResponseEnumeration.OK, string.Empty));
                        break;
                    default:
                        this.LoginCompleted(this, new LoginEventArgs(ProviderResponseEnumeration.Failed, loginModel.Status));
                        break;
                }
            }
        }
        #endregion

    }
}
